
using Admin2505.Application.Common;
using Admin2505.Application.Common.Interfaces;
using Admin2505.Application.Dto;
using Admin2505.Domain.Common;
using Admin2505.Domain.Entityes.App;
using Admin2505.Domain.Reposoitories;

namespace Admin2505.Application.Services;

public class UserService
{
    private readonly IRepository<AppUser> _userRepo;

    private readonly IPasswordHasher _passwordHasher;
private readonly IRepository<AppUserRole> _userRoleRepo;

public UserService(IRepository<AppUser> userRepo, IRepository<AppUserRole> userRoleRepo, IPasswordHasher passwordHasher)
{
    _userRepo = userRepo;
    _userRoleRepo = userRoleRepo;
    _passwordHasher = passwordHasher;
}
//创建用户
    public async Task<AppUser> CreateUserAsync(string userName , string password)
    {
        var users = await _userRepo.GetAllAsync();
        if(users.Any(u=>u.Username==userName))
        throw new Exception("用户已经存在");
        var salt = _passwordHasher.GenerateSalt();
        var hash = _passwordHasher.HasPassword(password,salt);
        var user = new AppUser(userName,hash,salt);
        await _userRepo.CreateAsync(user);


        return user;
    }
    //修改密码
    public async Task ChangePasswordAsync(Guid userId,string newPassword)
    {
           var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception ("用户不存在");
           var salt = _passwordHasher.GenerateSalt();
           var hash = _passwordHasher.HasPassword(newPassword ,salt);
           user.SetPassword(hash,salt);
           await _userRepo.UpdateAsync(user); 
    }
    //分配角色
    public async Task AssignRoleAsync(Guid userId,AppRole role)
    {
      var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception("用户不存在00");
        user.AssignRole(role);
        await _userRepo.UpdateAsync(user); 
    }

    //移除角色
    public async Task RemoveRoleAsync(Guid userId, AppRole role)
    {
        var user = await _userRepo.GetByIdAsync(userId) ?? throw new Exception("用户不存在");
        // 找到对应的用户-角色关联
        var userRole = (await _userRoleRepo.GetAllAsync()).FirstOrDefault(x => x.UserId == userId && x.RoleId == role.Id);
        if (userRole != null)
        {
            await _userRoleRepo.DeleteAsync(userRole.Id);
        }
    }
    //查询用户
    public async Task<AppUser?> GetUserByAsync (Guid RoleId){
        return await _userRepo.GetByIdAsync(RoleId);
    }
    // public async Task<IEnumerable<AppUser>> GetAllUsersAsync()
    // {
    //     return await _userRepo.GetAllAsync();
    // }
    public async Task<PageResultDto<AppUser>> GetPageUserAsync(int PageIndex,int PageSize)
    {
        return await _userRepo.GetPagedAsync(PageIndex,PageSize);
    }

    public async Task<ApiResult> UpdateUserInfo(Guid userId,UpdateUserDto update)
    {
        var user = await _userRepo.GetByIdAsync(userId);
        if (user==null)
        {
            return  ApiResult.Fail();
        }
        user.Nickname = update.Nickname;
        user.Avatar = update.Telephone;
        user.Email = update.Email;
        await _userRepo.UpdateAsync(user);
        return ApiResult.Sucess(user,"更新用户基本资料成功");
    }
    public async Task<ApiResult> EnableUser(Guid userId)
    {
        var user = await _userRepo.GetByIdAsync(userId);
        if (user==null)
        {
            return ApiResult.Fail();
        }
        if (user.IsActived ==true)
        {
            return ApiResult.Fail(40040,"该用户已经处于启动状态");
        }
        user.IsActived =true;
        await _userRepo.UpdateAsync(user);
        return ApiResult.Sucess(user,"启用指定用户成功");
        
    }
    public async Task<ApiResult> DisableUser(Guid userId)
    {
        var user = await _userRepo.GetByIdAsync(userId);
        if(user==null)
        {
            return ApiResult.Fail();
        }
        if (user.IsActived ==true)
        {
            return ApiResult.Fail(40040,"该用户已经处于禁用状态");
        }
        user.IsActived =true;
        await _userRepo.UpdateAsync(user);
        return ApiResult.Sucess(user,"禁用指定用户成功");
    }
    public async Task<ApiResult> DeleteUser(Guid userId)
    {
        
        var user = await _userRepo.GetByIdAsync(userId);
        if(user==null)
        {
            return ApiResult.Fail();
        }
        await _userRepo.UpdateAsync(user);
        return ApiResult.Sucess(user,"删除/注销用户成功");
    }
    public async Task<ApiResult> UpdateAvatar(Guid userId,Guid fileId)
    {
        //这里假设fileid已经上传并与用户绑定，实际项目中可能需要更多参数
        //这里只做演示，实际应该传入userID 和fileid
        var user = await _userRepo.GetByIdAsync(userId);
        if(user==null)
        {
            return ApiResult.Fail(40040,"用户不存在");
        }
        if(user.IsActived == false)
        {
            return ApiResult.Fail(400405,"用户已经禁用，无法更新头像");
        }
        user.Avatar=fileId.ToString();
        await _userRepo.UpdateAsync(user);
        return ApiResult.Fail(40050,"请实现 UpdateAvatar 具体逻辑");
    }
    public async Task<ApiResult> HasPerminssion(Guid userId)
    {
        //这里只做演示，实际应传入 userId 和 perminssin、roleId
        var user = await _userRepo.GetByIdAsync(userId);
        if(user==null)
        {
            return ApiResult.Fail(40040,"用户不存在");
        }
        if(user.IsActived == false)
        {
            return ApiResult.Fail(400405,"用户已经禁用，无法更新头像");
        }
        var hasPerminssion = user.HasPermission("Order.Create");
        if (hasPerminssion)
        {
            return ApiResult.Sucess(true,"用户用权限");
        }
        else
        {
            return ApiResult.Sucess(400450,"用户没有权限");

        }

    }
}
